﻿using ArtMath.Core.Data;
using System;
using System.Collections.Generic;

namespace ArtMath.PointCollection
{
    [Serializable]
    public class DiscontinuityPoint : PointCollectionBase
    {
        public HashSet<PointD> Points;
        public DiscontinuityPoint()
        {
            Points = new HashSet<PointD>();
        }
        public DiscontinuityPoint(IEnumerable<PointD> collection)
        {
            Points = new HashSet<PointD>(collection);
        }
        public DiscontinuityPoint(HashSet<PointD> set)
        {
            Points = set;
        }
        public DiscontinuityPoint(params PointD[] pts)
        {
            Points = new HashSet<PointD>(pts);
        }
        public override bool Contains(PointD pt)
        {
            return Points != null && Points.Contains(pt) && AfterContains(pt);
        }

        public override PointD? GetNearestPoint(PointD pt)
        {
            if (Points == null) return null;
            PointD? res = null;
            double minDist = double.PositiveInfinity;
            foreach (PointD item in Points)
            {
                if (!AfterContains(pt)) continue;
                double dist = pt.DistanceTo(item);
                if (dist < minDist)
                {
                    minDist = dist;
                    res = item;
                }
            }
            return res;
        }

        protected override PointCollectionBase Intersect(PointCollectionBase collection)
        {
            if (Points == null) return Empty.Instance;
            HashSet<PointD> set = new HashSet<PointD>();
            foreach (PointD item in Points)
            {
                if (collection.Contains(item))
                {
                    set.Add(item);
                }
            }
            if (set.Count == 0) return Empty.Instance;
            return AfterIntersect(collection.AfterIntersect(new DiscontinuityPoint(set)));
        }
    }
}
